using System.Buffers;
using System.IO.Pipelines;
using System.Text;
using System.Text.Json.Nodes;
using ExchangeClient.Abstractions;
using ExchangeClient.Abstractions.Model;
using HKH.Mef2.Integration;
using HKH.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using SyncService.Abstractions.Events;
using SyncService.Abstractions.Services;
using SyncService.Results;

namespace SyncService.WebHost.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class SyncController : MefControllerBase
    {
        private readonly ILogger<SyncController> _logger;
        private readonly IMemoryCache _cache;

        public SyncController(CompositionContainer mefContainer, ILogger<SyncController> logger, IMemoryCache cache)
            : base(mefContainer)
        {
            _logger = logger;
            _cache = cache;
        }

        [HttpPost]
        [Route("AssetHandler")]
        public async Task<object> YideaAssetHandler([FromQuery] string? nonce, [FromQuery] string? timestamp, [FromHeader(Name = "X-YIDEA-Signature")] string? signature, [FromHeader(Name = "X-YIDEA-DeliverId")] string? deliverId)
        {
            if (string.IsNullOrEmpty(deliverId)) //this is test request for add event handler
            {
                return "ok";
            }

            if (_cache.TryGetValue(deliverId, out var value))
            {
                _logger.LogDebug($"请求正在处理，忽略此重复请求：DeliverId={deliverId}, TimeStamp={timestamp}");
                return "ok";
            }
            string body = await GetBodyAsync();
            if (!string.IsNullOrEmpty(body))
            {
                _cache.Set(deliverId, deliverId);
            }

            _logger.LogTrace($"收到资产信息同步请求：body: {body}");

            var eventHub = MefContainer.GetExport<IEventHub>();
            eventHub.ProcessYideaEvent(new RequestData(nonce ?? "", signature ?? "", timestamp ?? "", body, deliverId ?? ""), _cache);

            return "ok";
        }


#if DEBUG
        [HttpPost]
        [Route("AssetHandlerTest")]
        public object YideaAssetHandlerTest([FromQuery] string? nonce, [FromQuery] string? timestamp, [FromHeader(Name = "X-YIDEA-Signature")] string? signature, [FromHeader(Name = "X-YIDEA-DeliverId")] string? deliverId)
        {
            var body = "{\"op\":\"Create\",\"source\":{\"Type\":8,\"Id\":\"ACR202307240002\"},\"meta\":{\"audit\":\"7923a219-006a-4be3-ab5d-692ae6d63610\",\"batch\":\"49ef2bc6-2471-4046-b8f9-8cdcd60dd1f7\"},\"data\":{\"FormId\":\"bdbf225e-22b0-43b4-b8fe-4a593e715c79\",\"FormName\":\"资产清理报废\",\"FormType\":12,\"Operation\":0,\"OperatedTime\":\"2023-07-24 10:02:25\",\"ApprovalInformation\":null,\"Id\":119945,\"SerialNo\":\"ACR202307240002\",\"ClearDate\":\"2023-07-24 02:01:25\",\"ClearUser\":\"david.huang 黄太玉\",\"Comment\":\"说明\",\"CreateUserId\":202755,\"EnterpriseId\":155307,\"CreateDate\":\"2023-07-24 10:02:24\",\"IsDelete\":false,\"SignatureStatus\":4,\"SignaturePicPath\":null,\"UpdateUser\":0,\"UpdateTime\":null,\"OwnerCompanyId\":193594,\"ReceiptDetails\":[{\"Id\":858682,\"AssetId\":12373379,\"AssetClearId\":119945,\"AssetOldUser\":\"david.huang 黄太玉\",\"AssetOldUseCompanyName\":\"134ba918644f975d\",\"AssetOldDepartmentName\":null,\"AssetOldAddressTypeName\":\"本地\",\"AssetOldAddress\":\"6楼\",\"AssetOldComment\":\"\",\"AssetOldAssetTypeName\":\"家具用具及其他类\",\"AssetOldName\":\"人体工学椅\",\"AssetOldSpecs\":\"高靠背+头枕\",\"AssetOldSNNo\":\"\",\"AssetOldMoney\":\"12,600.00\",\"AssetOldManager\":\"david.huang 黄太玉\",\"AssetOldOwnCompanyName\":\"134ba918644f975d\"}],\"table_1689924813690\":[{\"input_1689924818584\":\"测试员工\",\"input_1690163946679\":\"2023-07-24 11:20:10\",\"input_1689924824332\":\"同意审批\",\"input_1689933168431\":\"\",\"input_1689933178769\":\"\",\"subId\":\"efc3de1d-b378-47e8-a79d-dee4090c118b\",\"subIndex\":1}],\"input_1689838705994\":\"成功\",\"textarea_1689840651052\":\"失败了\",\"version\":\"bdbf225e-22b0-43b4-b8fe-4a593e715c79\",\"operator\":{\"id\":\"202755\",\"name\":\"david.huang 黄太玉\",\"username\":\"134ba918644f975d\"}}}";
            var eventHub = MefContainer.GetExport<IEventHub>();
            eventHub.ProcessYideaEvent(new RequestData(nonce ?? "", signature ?? "", timestamp ?? "", body, deliverId ?? ""), _cache);

            return "ok";
        }
#endif
        /// <summary>
        /// 获取请求的数据
        /// </summary>
        private async Task<string> GetBodyAsync()
        {
            var bodyReader = Request.BodyReader;
            ReadResult readResult = new ReadResult();
            while (true)
            {
                readResult = await bodyReader.ReadAsync();
                if (readResult.IsCompleted) { break; }
                bodyReader.AdvanceTo(readResult.Buffer.Start, readResult.Buffer.End);
            }
            var buffer = readResult.Buffer;
            bodyReader.AdvanceTo(readResult.Buffer.Start, readResult.Buffer.Start);

            return Encoding.UTF8.GetString(buffer.ToArray());
        }
    }
}